/*
 * Copyright (c) 2009-2010 HIT Microelectronic Center
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *
 * Authors: Gou Pengfei
 *          Jin Yinghan
 *
 * Date: Dec. 2009
 *
 */

#include "config/full_system.hh"
#include "config/the_isa.hh"
#include "config/use_checker.hh"
#include "cpu/activity.hh"
#include "cpu/simple_thread.hh"
#include "cpu/thread_context.hh"
//#include "cpu/edge/impl_specific.hh"
//#include "cpu/edge/impl.hh"
#include "cpu/edge/cpu.hh"
#include "cpu/edge/thread_context.hh"
#include "enums/MemoryMode.hh"
#include "sim/core.hh"
#include "sim/stat_control.hh"

#include "cpu/edge/atomic/impl.hh"
#include "cpu/edge/atomic/atomic.hh"
#include "cpu/edge/atomic/atomic_dyn_inst.hh"
#include "cpu/edge/atomic/atomic_block.hh"

class BaseCPUParams;

using namespace TheISA;
using namespace std;

//EdgeCPU::EdgeCPU(BaseCPUParams *params)
//    : BaseCPU(params)
//{
//    edge_tracer = params->edge_tracer;
//}

//void
//EdgeCPU::regStats()
//{
//    BaseCPU::regStats();
//}

template <class Impl>
BaseEdgeCPU<Impl>::TickEvent::TickEvent(BaseEdgeCPU<Impl> *c)
    : Event(CPU_Tick_Pri), cpu(c)
{
}

template <class Impl>
void
BaseEdgeCPU<Impl>::TickEvent::process()
{
    cpu->tick();
}

template <class Impl>
const char *
BaseEdgeCPU<Impl>::TickEvent::description() const
{
    return "BaseEdgeCPU tick";
}

template <class Impl>
BaseEdgeCPU<Impl>::ActivateThreadEvent::ActivateThreadEvent()
    : Event(CPU_Switch_Pri)
{
}

template <class Impl>
void
BaseEdgeCPU<Impl>::ActivateThreadEvent::init(int thread_num,
                                           BaseEdgeCPU<Impl> *thread_cpu)
{
    tid = thread_num;
    cpu = thread_cpu;
}

template <class Impl>
void
BaseEdgeCPU<Impl>::ActivateThreadEvent::process()
{
    cpu->activateThread(tid);
}

template <class Impl>
const char *
BaseEdgeCPU<Impl>::ActivateThreadEvent::description() const
{
    return "BaseEdgeCPU \"Activate Thread\"";
}

template <class Impl>
BaseEdgeCPU<Impl>::DeallocateContextEvent::DeallocateContextEvent()
    : Event(CPU_Tick_Pri), tid(0), remove(false), cpu(NULL)
{
}

template <class Impl>
void
BaseEdgeCPU<Impl>::DeallocateContextEvent::init(int thread_num,
                                              BaseEdgeCPU<Impl> *thread_cpu)
{
    tid = thread_num;
    cpu = thread_cpu;
    remove = false;
}

template <class Impl>
void
BaseEdgeCPU<Impl>::DeallocateContextEvent::process()
{
    cpu->deactivateThread(tid);
    if (remove)
        cpu->removeThread(tid);
}

template <class Impl>
const char *
BaseEdgeCPU<Impl>::DeallocateContextEvent::description() const
{
    return "BaseEdgeCPU \"Deallocate Context\"";
}

template <class Impl>
BaseEdgeCPU<Impl>::BaseEdgeCPU(DerivEdgeCPUParams *params)
    : BaseCPU(params),
      itb(params->itb),
      dtb(params->dtb),
      preExecuteCPU(params->preExecuteCPU),
      tickEvent(this),
#ifndef NDEBUG
      instcount(0),
      blockcount(0),
#endif
      removeBlocksThisCycle(false),
      // Four-stages
      fetch(this, params),
      map(this, params),
      execute(this, params),
      commit(this,params),
      // Global register
      globalRegFile(this, params->numPhysIntRegs,
              params->numPhysFloatRegs),
      // RoB
      rob(this,
          params->numROBEntries, params->squashWidth,
          params->smtROBPolicy, params->smtROBThreshold,
          params->numThreads),
      // Time buffers
      timeBuffer(params->backComSize, params->forwardComSize),
      fetch2mapQueue(params->backComSize, params->forwardComSize),
      map2executeQueue(params->backComSize, params->forwardComSize),
      execute2commitQueue(params->backComSize, params->forwardComSize),

      activityRec(name(), NumStages,
                  params->backComSize + params->forwardComSize,
                  params->activity),
      // Init the global sequence number to be 1.
      globalSeqNum(1),
      drainCount(0),
      deferRegistration(params->defer_registration),
      numExeUnits(1),
      exeUnitsXMax(1),
      exeUnitsYMax(1)
{

    edge_tracer = params->edge_tracer;

    if (params->preExecuteMode && !preExecuteCPU) {
        panic("Pre execute mode need a valid preExecuteCPU.\n");
    }

    if (!deferRegistration) {
        _status = Running;
    } else {
        _status = Idle;
    }

    thread.resize(numThreads);
    tids.resize(numThreads);

    // The stages also need their CPU pointer setup.  However this
    // must be done at the upper level CPU because they have pointers
    // to the upper level CPU, and not this FullEdgeCPU.

    // Set up Pointers to the activeThreads list for each stage
    fetch.setActiveThreads(&activeThreads);
    map.setActiveThreads(&activeThreads);
    execute.setActiveThreads(&activeThreads);
    commit.setActiveThreads(&activeThreads);

    // Give each of the stages the time buffer they will use.
    fetch.setTimeBuffer(&timeBuffer);
    map.setTimeBuffer(&timeBuffer);
    execute.setTimeBuffer(&timeBuffer);
    commit.setTimeBuffer(&timeBuffer);

    // Also setup each of the stages' queues.
    fetch.setFetchQueue(&fetch2mapQueue);

    map.setMapQueue(&map2executeQueue);
    map.setFetchQueue(&fetch2mapQueue);

    execute.setExecuteQueue(&execute2commitQueue);
    execute.setMapQueue(&map2executeQueue);

    commit.setExecuteQueue(&execute2commitQueue);
    commit.setFetchQueue(&fetch2mapQueue);
    commit.setMapQueue(&map2executeQueue);
    commit.setExecuteStage(&execute);

    ThreadID active_threads = params->workload.size();

    if (active_threads > Impl::MaxThreads) {
        panic("Workload Size too large. Increase the 'MaxThreads'"
              "constant in your BaseEdgeCPU impl. file (e.g. cpu/edge/impl.hh) or "
              "edit your workload size.");
    }

    //Make Sure That this a Valid Architeture
    assert(params->numPhysIntRegs   >= numThreads * TheISA::NumIntRegs);
    assert(params->numPhysFloatRegs >= numThreads * TheISA::NumFloatRegs);

    for (ThreadID tid = 0; tid < numThreads; tid++) {
        activateThreadEvent[tid].init(tid, this);
        deallocateContextEvent[tid].init(tid, this);
    }
    // Setup the ROB for whichever stages need it.
    commit.setROB(&rob);

    lastRunningCycle = curTick;

    lastActivatedCycle = -1;

    contextSwitch = false;
    DPRINTF(EdgeCPU, "Creating BaseEdgeCPU object.\n");

    // Setup any thread state.
    this->thread.resize(this->numThreads);

    for (ThreadID tid = 0; tid < this->numThreads; ++tid) {

        if (tid < params->workload.size()) {
            DPRINTF(EdgeCPU, "Workload[%i] process is %#x",
                    tid, this->thread[tid]);
            this->thread[tid] = new typename BaseEdgeCPU<Impl>::Thread(
                    (typename Impl::CPU *)(this),
                    tid, params->workload[tid]);
        } else {
            //Allocate Empty thread so M5 can use later
            //when scheduling threads to CPU
            Process* dummy_proc = NULL;

            this->thread[tid] = new typename BaseEdgeCPU<Impl>::Thread(
                    (typename Impl::CPU *)(this),
                    tid, dummy_proc);
        }

        ThreadContext *tc;
        // Setup the TC that will serve as the interface to the threads/CPU.
        EdgeThreadContext<Impl> *edge_tc = new EdgeThreadContext<Impl>;
        tc = edge_tc;

        edge_tc->cpu = (typename Impl::CPU *)(this);
        assert(edge_tc->cpu);
        edge_tc->thread = this->thread[tid];

       // Give the thread the TC.
        this->thread[tid]->tc = tc;
        // Add the TC to the CPU's list of TC's.
        this->threadContexts.push_back(tc);
    }

    for (ThreadID tid = 0; tid < this->numThreads; tid++)
        this->thread[tid]->setFuncExeInst(0);

    lockAddr = 0;
    lockFlag = false;
}

template <class Impl>
BaseEdgeCPU<Impl>::~BaseEdgeCPU()
{
}

template <class Impl>
void
BaseEdgeCPU<Impl>::regStats()
{
    BaseCPU::regStats();

    // Register any of the BaseEdgeCPU's stats here.
    timesIdled
        .name(name() + ".timesIdled")
        .desc("Number of times that the entire CPU went into an idle state and"
              " unscheduled itself")
        .prereq(timesIdled);

    idleCycles
        .name(name() + ".idleCycles")
        .desc("Total number of cycles that the CPU has spent unscheduled due "
              "to idling")
        .prereq(idleCycles);

    committedBlocks
        .init(numThreads)
        .name(name() + ".committedInstBlocks")
        .desc("Number of Instruction Blocks Simulated");
        
    committedInsts
        .init(numThreads)
        .name(name() + ".committedInsts")
        .desc("Number of Instructions executed including register writes/reads");
        
    totalCommittedBlocks
        .name(name() + ".committedInstBlocks_total")
        .desc("Number of Instruction Blocks Simulated");
        
    totalCommittedInsts
        .name(name() + ".committedInsts_total")
        .desc("Number of Instructions executed including register writes/reads");
        
    cpi
        .name(name() + ".cpi")
        .desc("CPI: Cycles Per Instruction")
        .precision(6);
    cpi = numCycles / committedInsts;

    totalCpi
        .name(name() + ".cpi_total")
        .desc("CPI: Total CPI of All Threads")
        .precision(6);
    totalCpi = numCycles / totalCommittedInsts;

    ipc
        .name(name() + ".ipc")
        .desc("IPC: Instructions Per Cycle")
        .precision(6);
    ipc =  committedInsts / numCycles;

    totalIpc
        .name(name() + ".ipc_total")
        .desc("IPC: Total IPC of All Threads")
        .precision(6);
    totalIpc =  totalCommittedInsts / numCycles;

    this->fetch.regStats();
    this->map.regStats();
    this->execute.regStats();
    this->commit.regStats();
}

template <class Impl>
Port *
BaseEdgeCPU<Impl>::getPort(const std::string &if_name, int idx)
{
    if (if_name == "dcache_port")
        return execute.getDcachePort();
    else if (if_name == "icache_port")
        return fetch.getIcachePort();
    else
        panic("No Such Port\n");
}

template <class Impl>
void
BaseEdgeCPU<Impl>::tick()
{
    DPRINTF(EdgeTickSeparation, "\n\n"
        "--------------------------------\n"
        "EdgeCPU: Ticking main, BaseEdgeCPU.\n"
        "--------------------------------\n"
        "--------------------------------\n");

    ++numCycles;

//    activity = false;

    //Tick each of the stages
    fetch.tick();
    map.tick();
    execute.tick();
    commit.tick();

    doContextSwitch();

    // Now advance the time buffers
    timeBuffer.advance();

    fetch2mapQueue.advance();
    map2executeQueue.advance();
    execute2commitQueue.advance();

    activityRec.advance();

    if (removeBlocksThisCycle) {
        cleanUpRemovedBlocks();
    }

    if (!tickEvent.scheduled()) {
        if (_status == SwitchedOut ||
            getState() == SimObject::Drained) {
            DPRINTF(EdgeCPU, "Switched out!\n");
            // increment stat
            lastRunningCycle = curTick;
        } else if (!activityRec.active() || _status == Idle) {
            DPRINTF(EdgeCPU, "Idle!\n");
            lastRunningCycle = curTick;
            timesIdled++;
        } else {
            schedule(tickEvent, nextCycle(curTick + ticks(1)));
            DPRINTF(EdgeCPU, "Scheduling next tick!\n");
        }
    }

    updateThreadPriority();
}

template <class Impl>
void
BaseEdgeCPU<Impl>::init()
{
    BaseCPU::init();

    // Set inSyscall so that the CPU doesn't squash when initially
    // setting up registers.
    for (ThreadID tid = 0; tid < numThreads; ++tid)
        thread[tid]->inSyscall = true;

    // Clear inSyscall.
    for (int tid = 0; tid < numThreads; ++tid)
        thread[tid]->inSyscall = false;

    // Initialize stages.
    fetch.initStage();
    //map.initStage();
    execute.initStage();
    commit.initStage();

    commit.setThreads(thread);

}

template <class Impl>
void
BaseEdgeCPU<Impl>::activateThread(ThreadID tid)
{
    list<ThreadID>::iterator isActive =
        std::find(activeThreads.begin(), activeThreads.end(), tid);

    DPRINTF(EdgeCPU, "[tid:%i]: Calling activate thread.\n", tid);

    if (isActive == activeThreads.end()) {
        DPRINTF(EdgeCPU, "[tid:%i]: Adding to active threads list\n",
                tid);

        activeThreads.push_back(tid);
    }
}

template <class Impl>
void
BaseEdgeCPU<Impl>::deactivateThread(ThreadID tid)
{
    //Remove From Active List, if Active
    list<ThreadID>::iterator thread_it =
        std::find(activeThreads.begin(), activeThreads.end(), tid);

    DPRINTF(EdgeCPU, "[tid:%i]: Calling deactivate thread.\n", tid);

    if (thread_it != activeThreads.end()) {
        DPRINTF(EdgeCPU,"[tid:%i]: Removing from active threads list\n",
                tid);
        activeThreads.erase(thread_it);
    }
}

template <class Impl>
Counter
BaseEdgeCPU<Impl>::totalInstructionBlocks() const
{
    Counter total(0);

    ThreadID size = thread.size();
    for (ThreadID i = 0; i < size; i++)
        total += thread[i]->numBlock;

    return total;
}

template <class Impl>
void
BaseEdgeCPU<Impl>::activateContext(ThreadID tid, int delay)
{
    // Needs to set each stage to running as well.
    if (delay){
        DPRINTF(EdgeCPU, "[tid:%i]: Scheduling thread context to activate "
                "on cycle %d\n", tid, curTick + ticks(delay));
        scheduleActivateThreadEvent(tid, delay);
    } else {
        activateThread(tid);
    }

    if (lastActivatedCycle < curTick) {
        scheduleTickEvent(delay);

        // Be sure to signal that there's some activity so the CPU doesn't
        // deschedule itself.
        activityRec.activity();
        fetch.wakeFromQuiesce();

        lastActivatedCycle = curTick;

        _status = Running;
    }
}

template <class Impl>
bool
BaseEdgeCPU<Impl>::deallocateContext(ThreadID tid, bool remove, int delay)
{
    // Schedule removal of thread data from CPU
    if (delay){
        DPRINTF(EdgeCPU, "[tid:%i]: Scheduling thread context to deallocate "
                "on cycle %d\n", tid, curTick + ticks(delay));
        scheduleDeallocateContextEvent(tid, remove, delay);
        return false;
    } else {
        deactivateThread(tid);
        if (remove)
            removeThread(tid);
        return true;
    }
}

template <class Impl>
void
BaseEdgeCPU<Impl>::suspendContext(ThreadID tid)
{
    DPRINTF(EdgeCPU,"[tid: %i]: Suspending Thread Context.\n", tid);
    bool deallocated = deallocateContext(tid, false, 1);
    // If this was the last thread then unschedule the tick event.
    if ((activeThreads.size() == 1 && !deallocated) ||
        activeThreads.size() == 0)
        unscheduleTickEvent();
    _status = Idle;
}

template <class Impl>
void
BaseEdgeCPU<Impl>::haltContext(ThreadID tid)
{
    //For now, this is the same as deallocate
    DPRINTF(EdgeCPU,"[tid:%i]: Halt Context called. Deallocating", tid);
    deallocateContext(tid, true, 1);
}

template <class Impl>
void
BaseEdgeCPU<Impl>::insertThread(ThreadID tid)
{
    DPRINTF(EdgeCPU,"[tid:%i] Initializing thread into CPU");
    panic("insertThread method Unimplemented yet!\n");
}

template <class Impl>
void
BaseEdgeCPU<Impl>::removeThread(ThreadID tid)
{
    DPRINTF(EdgeCPU,"[tid:%i] Removing thread context from CPU.\n", tid);
    panic("removeThread method unimplemented yet!\n");
}


template <class Impl>
void
BaseEdgeCPU<Impl>::activateWhenReady(ThreadID tid)
{
    DPRINTF(EdgeCPU,"[tid:%i]: Checking if resources are available for incoming"
            "(e.g. PhysRegs/ROB/IQ/LSQ) \n",
            tid);

    panic("activeWhenReady method unimplemented yet!\n");
}

template <class Impl>
void
BaseEdgeCPU<Impl>::trap(Fault fault, ThreadID tid)
{
    // Pass the thread's TC into the invoke method.
    fault->invoke(this->threadContexts[tid]);
}

template <class Impl>
void
BaseEdgeCPU<Impl>::syscall(int64_t callnum, ThreadID tid)
{
    DPRINTF(EdgeCPU, "[tid:%i] Executing syscall().\n\n", tid);

    DPRINTF(Activity,"Activity: syscall() called.\n");

    // Temporarily increase this by one to account for the syscall
    // instruction.
    ++(this->thread[tid]->funcExeInst);

    // Execute the actual syscall.
    this->thread[tid]->syscall(callnum);

    // Decrease funcExeInst by one as the normal commit will handle
    // incrementing it.
    --(this->thread[tid]->funcExeInst);
}

template <class Impl>
void
BaseEdgeCPU<Impl>::serialize(std::ostream &os)
{
    SimObject::State so_state = SimObject::getState();
    SERIALIZE_ENUM(so_state);
    BaseCPU::serialize(os);
    nameOut(os, csprintf("%s.tickEvent", name()));
    tickEvent.serialize(os);

    // Use SimpleThread's ability to checkpoint to make it easier to
    // write out the registers.  Also make this static so it doesn't
    // get instantiated multiple times (causes a panic in statistics).
    static SimpleThread temp;

    ThreadID size = thread.size();
    for (ThreadID i = 0; i < size; i++) {
        nameOut(os, csprintf("%s.xc.%i", name(), i));
        temp.copyTC(thread[i]->getTC());
        temp.serialize(os);
    }
}

template <class Impl>
void
BaseEdgeCPU<Impl>::unserialize(Checkpoint *cp, const std::string &section)
{
    SimObject::State so_state;
    UNSERIALIZE_ENUM(so_state);
    BaseCPU::unserialize(cp, section);
    tickEvent.unserialize(cp, csprintf("%s.tickEvent", section));

    // Use SimpleThread's ability to checkpoint to make it easier to
    // read in the registers.  Also make this static so it doesn't
    // get instantiated multiple times (causes a panic in statistics).
    static SimpleThread temp;

    ThreadID size = thread.size();
    for (ThreadID i = 0; i < size; i++) {
        temp.copyTC(thread[i]->getTC());
        temp.unserialize(cp, csprintf("%s.xc.%i", section, i));
        thread[i]->getTC()->copyArchRegs(temp.getTC());
        thread[i]->getTC()->activate(0);

        if (commit.simPointSim) {
            commit.simPoint->unserialize(cp, csprintf("%s.xc.%i", section, i));
        }
    }
}

template <class Impl>
unsigned int
BaseEdgeCPU<Impl>::drain(Event *drain_event)
{
    DPRINTF(EdgeCPU, "Switching out\n");

    // If the CPU isn't doing anything, then return immediately.
    if (_status == Idle || _status == SwitchedOut) {
        return 0;
    }

    drainCount = 0;
    fetch.drain();

    // Wake the CPU and record activity so everything can drain out if
    // the CPU was not able to immediately drain.
    if (getState() != SimObject::Drained) {
        // A bit of a hack...set the drainEvent after all the drain()
        // calls have been made, that way if all of the stages drain
        // immediately, the signalDrained() function knows not to call
        // process on the drain event.
        drainEvent = drain_event;

        wakeCPU();
        activityRec.activity();

        return 1;
    } else {
        return 0;
    }
}

template <class Impl>
void
BaseEdgeCPU<Impl>::resume()
{
    fetch.resume();
    map.resume();
    execute.resume();
    commit.resume();

    changeState(SimObject::Running);

    if (_status == SwitchedOut || _status == Idle)
        return;

    if (!tickEvent.scheduled())
        schedule(tickEvent, nextCycle());
    _status = Running;
}

template <class Impl>
void
BaseEdgeCPU<Impl>::signalDrained()
{
    if (++drainCount == NumStages) {
        if (tickEvent.scheduled())
            tickEvent.squash();

        changeState(SimObject::Drained);

        BaseCPU::switchOut();

        if (drainEvent) {
            drainEvent->process();
            drainEvent = NULL;
        }
    }
    assert(drainCount <= 5);
}

template <class Impl>
void
BaseEdgeCPU<Impl>::switchOut()
{
    fetch.switchOut();
    map.switchOut();
    execute.switchOut();
    commit.switchOut();

    blockList.clear();
    while (!blockRemoveList.empty()) {
        blockRemoveList.pop();
    }

    _status = SwitchedOut;

   if (tickEvent.scheduled())
        tickEvent.squash();
}

template <class Impl>
void
BaseEdgeCPU<Impl>::takeOverFrom(BaseCPU *oldCPU)
{
    // Flush out any old data from the time buffers.
    for (int i = 0; i < timeBuffer.getSize(); ++i) {
        timeBuffer.advance();

        fetch2mapQueue.advance();
    map2executeQueue.advance();
    execute2commitQueue.advance();

    }

    activityRec.reset();

    BaseCPU::takeOverFrom(oldCPU, fetch.getIcachePort(), NULL); // Fix me!

    fetch.takeOverFrom();
    map.takeOverFrom();
    execute.takeOverFrom();
    commit.takeOverFrom();

    assert(!tickEvent.scheduled());

    // @todo: Figure out how to properly select the tid to put onto
    // the active threads list.
    ThreadID tid = 0;

    list<ThreadID>::iterator isActive =
        std::find(activeThreads.begin(), activeThreads.end(), tid);

    if (isActive == activeThreads.end()) {
        //May Need to Re-code this if the delay variable is the delay
        //needed for thread to activate
        DPRINTF(EdgeCPU, "Adding Thread %i to active threads list\n",
                tid);

        activeThreads.push_back(tid);
    }

    // Set all statuses to active, schedule the CPU's tick event.
    // @todo: Fix up statuses so this is handled properly
    ThreadID size = threadContexts.size();
    for (ThreadID i = 0; i < size; ++i) {
        ThreadContext *tc = threadContexts[i];
        if (tc->status() == ThreadContext::Active && _status != Running) {
            _status = Running;
            schedule(tickEvent, nextCycle());
        }
    }
    if (!tickEvent.scheduled())
        schedule(tickEvent, nextCycle());
}

template <class Impl>
TheISA::MiscReg
BaseEdgeCPU<Impl>::readMiscRegNoEffect(int misc_reg, ThreadID tid)
{
    return this->isa[tid].readMiscRegNoEffect(misc_reg);
}

template <class Impl>
TheISA::MiscReg
BaseEdgeCPU<Impl>::readMiscReg(int misc_reg, ThreadID tid)
{
    return this->isa[tid].readMiscReg(misc_reg, tcBase(tid));
}

template <class Impl>
void
BaseEdgeCPU<Impl>::setMiscRegNoEffect(int misc_reg,
        const TheISA::MiscReg &val, ThreadID tid)
{
    this->isa[tid].setMiscRegNoEffect(misc_reg, val);
}

template <class Impl>
void
BaseEdgeCPU<Impl>::setMiscReg(int misc_reg,
        const TheISA::MiscReg &val, ThreadID tid)
{
    this->isa[tid].setMiscReg(misc_reg, val, tcBase(tid));
}

template <class Impl>
uint64_t
BaseEdgeCPU<Impl>::readIntReg(int reg_idx)
{
    return globalRegFile.readIntReg(reg_idx);
}

template <class Impl>
FloatReg
BaseEdgeCPU<Impl>::readFloatReg(int reg_idx)
{
    return globalRegFile.readFloatReg(reg_idx);
}

template <class Impl>
FloatRegBits
BaseEdgeCPU<Impl>::readFloatRegBits(int reg_idx)
{
    return globalRegFile.readFloatRegBits(reg_idx);
}

template <class Impl>
void
BaseEdgeCPU<Impl>::setIntReg(int reg_idx, uint64_t val)
{
    globalRegFile.setIntReg(reg_idx, val);
}

template <class Impl>
void
BaseEdgeCPU<Impl>::setFloatReg(int reg_idx, FloatReg val)
{
    globalRegFile.setFloatReg(reg_idx, val);
}

template <class Impl>
void
BaseEdgeCPU<Impl>::setFloatRegBits(int reg_idx, FloatRegBits val)
{
    globalRegFile.setFloatRegBits(reg_idx, val);
}

template <class Impl>
uint64_t
BaseEdgeCPU<Impl>::readArchIntReg(int reg_idx, ThreadID tid)
{
    return globalRegFile.readIntReg(reg_idx);
}

template <class Impl>
float
BaseEdgeCPU<Impl>::readArchFloatReg(int reg_idx, ThreadID tid)
{
    int idx = reg_idx + TheISA::NumIntRegs;

    return globalRegFile.readFloatReg(idx);
}

template <class Impl>
uint64_t
BaseEdgeCPU<Impl>::readArchFloatRegInt(int reg_idx, ThreadID tid)
{
    int idx = reg_idx + TheISA::NumIntRegs;

    return globalRegFile.readFloatRegBits(idx);
}

template <class Impl>
void
BaseEdgeCPU<Impl>::setArchIntReg(int reg_idx, uint64_t val, ThreadID tid)
{
    PhysRegIndex phys_reg = reg_idx;

    globalRegFile.setIntReg(phys_reg, val);
}

template <class Impl>
void
BaseEdgeCPU<Impl>::setArchFloatReg(int reg_idx, float val, ThreadID tid)
{
    int idx = reg_idx + TheISA::NumIntRegs;

    globalRegFile.setFloatReg(idx, val);
}

template <class Impl>
void
BaseEdgeCPU<Impl>::setArchFloatRegInt(int reg_idx, uint64_t val, ThreadID tid)
{
    int idx = reg_idx + TheISA::NumIntRegs;

    globalRegFile.setFloatRegBits(idx, val);
}

template<class Impl>
uint64_t
BaseEdgeCPU<Impl>::getBlockPC(ThreadID tid)
{
    return commit.readPC(tid);
}

template<class Impl>
void
BaseEdgeCPU<Impl>::setBlockPC(Addr val, ThreadID tid)
{
    commit.setPC(val, tid);
}

template <class Impl>
uint64_t
BaseEdgeCPU<Impl>::readPC(ThreadID tid)
{
    return commit.readPC(tid);
}

template <class Impl>
void
BaseEdgeCPU<Impl>::setPC(Addr new_PC, ThreadID tid)
{
    commit.setPC(new_PC, tid);
}

template <class Impl>
uint64_t
BaseEdgeCPU<Impl>::readNextPC(ThreadID tid)
{
    return commit.readNextPC(tid);
}

template <class Impl>
void
BaseEdgeCPU<Impl>::setNextPC(uint64_t val, ThreadID tid)
{
    commit.setNextPC(val, tid);
}

// @todo: Next NPC should not be handled through fetch
// stage.
template <class Impl>
uint64_t
BaseEdgeCPU<Impl>::readNextNPC(ThreadID tid)
{
    return fetch.readNextNPC(tid);
}

template <class Impl>
void
BaseEdgeCPU<Impl>::setNextNPC(uint64_t val, ThreadID tid)
{
    fetch.setNextNPC(val, tid);
}

template <class Impl>
void
BaseEdgeCPU<Impl>::squashFromTC(ThreadID tid)
{
    this->thread[tid]->inSyscall = true;
    this->commit.generateTCEvent(tid);
}

template <class Impl>
typename BaseEdgeCPU<Impl>::ListIt
BaseEdgeCPU<Impl>::addInstBlock(EdgeBlockPtr &block)
{
    blockList.push_back(block);

    DPRINTF(EdgeCPU, "Adding inst block[Bid:%lli] into block list.\n",
                              block->getBlockID());

    return --(blockList.end());
}

template <class Impl>
void
BaseEdgeCPU<Impl>::instBlockDone(ThreadID tid,int committed_insts )
{

    thread[tid]->numBlock++;
    //thread[tid]->numInsts++;
    thread[tid]->numBlocks++;

    committedBlocks[tid]++;
    committedInsts[tid] += committed_insts;

    totalCommittedBlocks++;
    totalCommittedInsts += committed_insts;

    // Check for inst-block-count-based events.
    comInstEventQueue[tid]->serviceEvents(thread[tid]->numBlock);
}

template <class Impl>
void
BaseEdgeCPU<Impl>::addToBlockRemoveList(EdgeBlockPtr &block)
{
    removeBlocksThisCycle = true;

    blockRemoveList.push(block->getBlockListIt());
}

template <class Impl>
void
BaseEdgeCPU<Impl>::removeFrontBlock(EdgeBlockPtr &block)
{
    DPRINTF(EdgeCPU, "Removing committed block [tid:%i] PC %#x "
            "[id:%lli]\n",
            block->getTid(), block->getStartPC(), block->getBlockID());

    removeBlocksThisCycle = true;

    // Remove the front instruction.
    blockRemoveList.push(block->getBlockListIt());
}

template <class Impl>
int
BaseEdgeCPU<Impl>::removeBlocksNotInROB(ThreadID tid)
{
    DPRINTF(EdgeCPU, "Thread %i: Deleting inst blocks from inst block"
            " list.\n", tid);

    ListIt end_it;

    bool rob_empty = false;

    if (blockList.empty()) {
        return 0;
    } else if (rob.isEmpty(/*tid*/)) {
        DPRINTF(EdgeCPU, "ROB is empty, squashing all inst blocks.\n");
        end_it = blockList.begin();
        rob_empty = true;
    } else {
        end_it = (rob.readTailInstBlock(tid))->getBlockListIt();
        DPRINTF(EdgeCPU, "ROB is not empty, squashing inst blocks not in ROB.\n");
    }

    removeBlocksThisCycle = true;

    ListIt inst_block_it = blockList.end();

    inst_block_it--;

    int squashed_num = 0;

    // Walk through the instruction list, removing any instructions
    // that were inserted after the given instruction iterator, end_it.
    while (inst_block_it != end_it) {
        assert(!blockList.empty());
        squashed_num++;

        squashBlockIt(inst_block_it, tid);

        inst_block_it--;
    }

    // If the ROB was empty, then we actually need to remove the first
    // instruction as well.
    if (rob_empty) {
        squashed_num++;
        squashBlockIt(inst_block_it, tid);
    }

    return squashed_num;
}

template <class Impl>
void
BaseEdgeCPU<Impl>::removeBlocksUntil(const BlockSeqNum &seq_num, ThreadID tid)
{
    assert(!blockList.empty());

    removeBlocksThisCycle = true;

    ListIt block_iter = blockList.end();

    block_iter--;

    DPRINTF(EdgeCPU, "Deleting blocks from block "
            "list that are from [tid:%i] and above [id:%lli] (end=%lli).\n",
            tid, seq_num, (*block_iter)->getBlockID());

    while ((*block_iter)->getBlockID() > seq_num) {

        bool break_loop = (block_iter == blockList.begin());

        squashBlockIt(block_iter, tid);

        block_iter--;

        if (break_loop)
            break;
    }
}

template <class Impl>
inline void
BaseEdgeCPU<Impl>::squashBlockIt(const ListIt &blockIt, ThreadID tid)
{
    if ((*blockIt)->getTid() == tid) {
        DPRINTF(EdgeCPU, "Squashing block, "
                "[tid:%i] [id:%lli] PC %#x\n",
                (*blockIt)->getTid(),
                (*blockIt)->getBlockID(),
                (*blockIt)->getStartPC());

        // Mark it as squashed.
        (*blockIt)->setSquashed();

        // @todo: Formulate a consistent method for deleting
        // inst blocks from the inst block list
        blockRemoveList.push(blockIt);
    }
}

template <class Impl>
void
BaseEdgeCPU<Impl>::cleanUpRemovedBlocks()
{
    while (!blockRemoveList.empty()) {
        DPRINTF(EdgeCPU, "Removing block, "
                "[tid:%i] [Bid:%lli] start PC %#x, current ref count is %i.\n",
                (*blockRemoveList.front())->getTid(),
                (*blockRemoveList.front())->getBlockID(),
                (*blockRemoveList.front())->getStartPC(),
                (*blockRemoveList.front())->getCount());

        ListIt it = blockRemoveList.front();

        (*it)->removeAllInsts();

        DPRINTF(EdgeCPU, "Current ref count is %i.\n",
                (*blockRemoveList.front())->getCount());

        blockList.erase(it);

        blockRemoveList.pop();
    }

    removeBlocksThisCycle = false;
}

template<class Impl>
TheISA::BlockID
BaseEdgeCPU<Impl>::readHeadInstBlockID( ThreadID tid)
{
    return rob.readHeadInstBlockID(tid);
}
/*
template <class Impl>
void
BaseEdgeCPU<Impl>::removeAllInsts()
{
    instList.clear();
}
*/
template <class Impl>
void
BaseEdgeCPU<Impl>::dumpBlocks()
{
    int num = 0;

    ListIt block_list_it = blockList.begin();

    cprintf("Dumping block List\n");

    while (block_list_it != blockList.end()) {
        cprintf("Block[id:%lli] start at 0x%lli\nBlock has %i insts\n",
                num, (*block_list_it)->getBlockID(),
                (*block_list_it)->getStartPC(),
                (*block_list_it)->getBlockSize());
#ifndef NDEBUG
        (*block_list_it)->dumpOutput();
#endif
        block_list_it++;
        ++num;
    }
}
/*
template <class Impl>
void
BaseEdgeCPU<Impl>::wakeDependents(DynInstPtr &inst)
{
    iew.wakeDependents(inst);
}
*/
template <class Impl>
void
BaseEdgeCPU<Impl>::wakeCPU()
{
    if (activityRec.active() || tickEvent.scheduled()) {
        DPRINTF(Activity, "CPU already running.\n");
        return;
    }

    DPRINTF(Activity, "Waking up CPU\n");

    idleCycles += tickToCycles((curTick - 1) - lastRunningCycle);
    numCycles += tickToCycles((curTick - 1) - lastRunningCycle);

    schedule(tickEvent, nextCycle());
}

template <class Impl>
ThreadID
BaseEdgeCPU<Impl>::getFreeTid()
{
    for (ThreadID tid = 0; tid < numThreads; tid++) {
        if (!tids[tid]) {
            tids[tid] = true;
            return tid;
        }
    }

    return InvalidThreadID;
}

template <class Impl>
void
BaseEdgeCPU<Impl>::doContextSwitch()
{
    if (contextSwitch) {

        //ADD CODE TO DEACTIVE THREAD HERE (???)

        ThreadID size = cpuWaitList.size();
        for (ThreadID tid = 0; tid < size; tid++) {
            activateWhenReady(tid);
        }

        if (cpuWaitList.size() == 0)
            contextSwitch = true;
    }
}

template <class Impl>
void
BaseEdgeCPU<Impl>::updateThreadPriority()
{
    if (activeThreads.size() > 1) {
        //DEFAULT TO ROUND ROBIN SCHEME
        //e.g. Move highest priority to end of thread list
        list<ThreadID>::iterator list_begin = activeThreads.begin();
//        list<ThreadID>::iterator list_end   = activeThreads.end();

        unsigned high_thread = *list_begin;

        activeThreads.erase(list_begin);

        activeThreads.push_back(high_thread);
    }
}

/*
template <class Impl>
void
BaseEdgeCPU<Impl>::updateOldestBlockPointer(){
    if((++oldestBlockPointer) == Impl::FrameNum)
        oldestBlockPointer = 0;
}

template <class Impl>
void
BaseEdgeCPU<Impl>::updateYoungestBlockPointer(){
    if((++youngestBlockPointer) == Impl::FrameNum)
        youngestBlockPointer = 0;
}
*/

